<!-- 进程管控 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px;">
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
          <span style="color:#d2d7e3;font-size:25px;margin-top:10px;padding-left:10px;">
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i>
              <div style="width: 420px;" slot="content">通过拖动表格行来重新排列顺序,
                系统按次序从上到下优先级执行。终端找到一条匹配的规则后将不再向下继续匹配规则。匹配不到规则将使用默认策略。</div>
            </el-tooltip>
          </span>
        </div>
      </div>
      <el-table stripe border :data="tableData" class="draggable-table" table-id="table1" row-key="RuleName"
        height="calc(100vh - 155px)" style="width: 100%; margin-top: 15px">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="策略名称" prop="RuleName" show-overflow-tooltip width="200px"></el-table-column>
        <el-table-column label="策略状态" show-overflow-tooltip prop="IsValid" width="160px">
          <template slot-scope="{row}">
            <span style="color:#67C23A" v-if="row.IsValid === 1" type="success">正常</span>
            <span style="color:#F56C6C" v-else type="danger">失效</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象类型" show-overflow-tooltip prop="DeviceObjType" width="120px">
          <template slot-scope="{row}">
            <span>{{ DeviceObjTypeFormatter(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px">
          <template slot-scope="{row}">
            <span>{{ getDeviceObjDisplay(row, DepartmentList, AssetsList) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" show-overflow-tooltip prop="Descp"></el-table-column>
        <el-table-column label="操作" fixed="right" width="220px">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="insertClick(scope.row, scope.$index)">插入</el-button>
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(tableData, scope.$index)"
              :disabled="scope.row.RuleID === 1744794439">删除</el-button> <!-- RuleID === 1744794439是默认策略 --->
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape="false" ref="dialog"
      :title="Action === 1 ? '添加策略' : Action === 2 ? '修改策略' : '插入策略'" :visible.sync="dialogVisible" v-el-drag-dialog
      width="1000px">
      <el-form label-width="160px" :model="accountForm" :rules="rules" ref="accountForm" class="ruleDialogForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">策略基本内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='策略名称：' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName" :disabled="Action === 2" maxlength="16"></el-input>
            </el-form-item>
            <el-form-item label='规则状态：' prop="IsValid" style="margin-top:-10px;">
              <el-radio v-model="accountForm.IsValid" :label="1">正常</el-radio>
              <el-radio v-model="accountForm.IsValid" :label="0">失效</el-radio>
            </el-form-item>
            <device-object-selector :form.sync="accountForm" />
            <el-form-item label="备注信息：" prop="Descp" style="margin-top:-15px;">
              <el-input placeholder="请输入备注" type="textarea" maxlength="50" :rows="3"
                v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleOther">
          <el-divider content-position="left">操作系统日志规则内容</el-divider>
          <el-col :xs="12" :sm="12" :lg="12">
            <el-form-item label='' prop="ExtOSLog">
              <el-checkbox style="width: 100%;" v-model="accountForm.ExtOSLog" :true-label="1"
                :false-label="0">采集系统拓展日志（进程创建、进程结束、网络访问、DNS解析）</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='' prop="BasicOSLog.global.Enabled" style="margin-top:-15px;">
              <el-checkbox style="width: 100%;" v-model="accountForm.BasicOSLog.global.Enabled" :true-label="1"
                :false-label="0" @change="changeSysLog">采集操作系统日志</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12">
            <el-form-item label='事件时间窗口：' prop="BasicOSLog.global.time_window" style="margin-top:-15px;">
              <el-input v-model.number="accountForm.BasicOSLog.global.time_window"
                oninput="value=value.replace(/[^0-9]/g,'')" maxlength="4"
                :disabled="accountForm.BasicOSLog.global.Enabled === 0"><span slot="append">分</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="11" :sm="11" :lg="11">
            <el-form-item label='轮询检测间隔：' prop="BasicOSLog.global.check_interval" label-width="120px"
              style="margin-top:-15px;">
              <el-input v-model.number="accountForm.BasicOSLog.global.check_interval"
                oninput="value=value.replace(/[^0-9]/g,'')" maxlength="2"
                :disabled="accountForm.BasicOSLog.global.Enabled === 0"><span slot="append">秒</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='事件分类：' prop="BasicOSLog.os_event_filter_rule.type" style="margin-top:-15px;">
              <el-checkbox-group v-model="accountForm.BasicOSLog.os_event_filter_rule.type">
                <el-checkbox style="width:70px;" :label="1"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">应用系统</el-checkbox>
                <el-checkbox style="width:70px;" :label="2"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">安全</el-checkbox>
                <el-checkbox style="width:70px;" :label="3"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">Setup</el-checkbox>
                <el-checkbox style="width:70px;" :label="4"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">系统</el-checkbox>
                <el-checkbox style="width:120px;" :label="5"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">Forwarded Events</el-checkbox>
                <el-checkbox style="width:80px;" :label="6"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">应用程序和服务日志</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label='事件等级：' prop="BasicOSLog.os_event_filter_rule.level" style="margin-top:-15px;">
              <el-checkbox-group v-model="accountForm.BasicOSLog.os_event_filter_rule.level">
                <el-checkbox style="width:70px;" :label="1"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">关键</el-checkbox>
                <el-checkbox style="width:70px;" :label="2"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">错误</el-checkbox>
                <el-checkbox style="width:70px;" :label="3"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">警告</el-checkbox>
                <el-checkbox style="width:70px;" :label="4"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">信息</el-checkbox>
                <el-checkbox style="width:70px;" :label="5"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">详细</el-checkbox>
                <el-checkbox style="width:70px;" :label="6"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">审核成功</el-checkbox>
                <el-checkbox style="width:70px;" :label="7"
                  :disabled="accountForm.BasicOSLog.global.Enabled === 0">审核失败</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label='事件ID：' prop="BasicOSLog.os_event_filter_rule.id_type" style="margin-top:-15px;">
              <el-radio style="width:70px;" v-model="accountForm.BasicOSLog.os_event_filter_rule.id_type" :label="0"
                :disabled="accountForm.BasicOSLog.global.Enabled === 0">全部</el-radio>
              <el-radio v-model="accountForm.BasicOSLog.os_event_filter_rule.id_type" :label="1"
                :disabled="accountForm.BasicOSLog.global.Enabled === 0">包括（事件ID，用逗号隔开）</el-radio>
              <el-radio style="width:70px;" v-model="accountForm.BasicOSLog.os_event_filter_rule.id_type" :label="2"
                :disabled="accountForm.BasicOSLog.global.Enabled === 0">排除（事件ID，用逗号隔开）</el-radio>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24" v-if="accountForm.BasicOSLog.os_event_filter_rule.id_type !== 0">
            <el-form-item label='' prop="BasicOSLog.os_event_filter_rule.id_list" style="margin-top:-15px;">
              <el-input v-model="accountForm.BasicOSLog.os_event_filter_rule.id_list"
                oninput="value=value.replace(/[^0-9,]/g,'')" placeholder="请输入事件ID，多个ID用逗号分隔"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleOther">
          <el-divider content-position="left">采集系统日志规则内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='' prop="ResPerfCheck.Enabled">
              <el-checkbox style="width: 100%;" v-model="accountForm.ResPerfCheck.Enabled" :true-label="1"
                :false-label="0">开启资产资源性能检测</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12">
            <el-form-item label='资产性能自检周期：' prop="ResPerfCheck.CheckInterval">
              <el-input v-model.number="accountForm.ResPerfCheck.CheckInterval" style="width:295px;"
                :disabled="accountForm.ResPerfCheck.Enabled === 0" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">秒</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="11" :sm="11" :lg="11">
            <el-form-item label='磁盘空间阈值：' prop="ResPerfCheck.MaxDiskPercent" label-width="120px">
              <el-input v-model.number="accountForm.ResPerfCheck.MaxDiskPercent"
                :disabled="accountForm.ResPerfCheck.Enabled === 0" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="3"><span slot="append">%</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12">
            <el-form-item label='CPU使用率连续：' prop="ResPerfCheck.MaxCPUKeepTimes">
              <el-input v-model.number="accountForm.ResPerfCheck.MaxCPUKeepTimes"
                :disabled="accountForm.ResPerfCheck.Enabled === 0" oninput="value=value.replace(/[^0-9]/g,'')"
                style="width:295px;" maxlength="4"><span slot="append">次</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="11" :sm="11" :lg="11">
            <el-form-item label=' ，超过' prop="ResPerfCheck.MaxCPUPercent" label-width="60px">
              <el-input v-model.number="accountForm.ResPerfCheck.MaxCPUPercent"
                :disabled="accountForm.ResPerfCheck.Enabled === 0" oninput="value=value.replace(/[^0-9]/g,'')"
                style="width:368px;" maxlength="3"><span slot="append">%</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12">
            <el-form-item label='内存使用率连续：' prop="ResPerfCheck.MaxMEMKeepTimes">
              <el-input v-model.number="accountForm.ResPerfCheck.MaxMEMKeepTimes"
                :disabled="accountForm.ResPerfCheck.Enabled === 0" oninput="value=value.replace(/[^0-9]/g,'')"
                style="width:295px;" maxlength="4"><span slot="append">次</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="11" :sm="11" :lg="11">
            <el-form-item label=' ，超过' prop="ResPerfCheck.MaxMEMPercent" label-width="60px">
              <el-input v-model.number="accountForm.ResPerfCheck.MaxMEMPercent"
                :disabled="accountForm.ResPerfCheck.Enabled === 0" oninput="value=value.replace(/[^0-9]/g,'')"
                style="width:368px;" maxlength="3"><span slot="append">%</span></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleOther">
          <el-divider content-position="left">系统拓展检测规则内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='系统拓展检测：' prop="SysEvent.HardwareChanged">
              <el-checkbox v-model="accountForm.SysEvent.HardwareChanged" :true-label="1"
                :false-label="0">硬件变更检测</el-checkbox>
              <el-checkbox v-model="accountForm.SysEvent.SoftwareChanged" :true-label="1"
                :false-label="0">软件变更检测</el-checkbox>
              <el-checkbox v-model="accountForm.SysEvent.USBStorage" :true-label="1"
                :false-label="0">USB插拔检测</el-checkbox>
              <el-checkbox v-model="accountForm.SysEvent.ExceptPowerOff" :true-label="1"
                :false-label="0">资产开机检测</el-checkbox>
              <el-checkbox v-model="accountForm.SysEvent.ConnectInternet" :true-label="1"
                :false-label="0">异常断电检测</el-checkbox>
              <el-checkbox v-model="accountForm.SysEvent.ConnectInternetNotLanNetcard" :true-label="1"
                :false-label="0">非法外联（能够接入互联网就形成事件）</el-checkbox>
              <el-checkbox v-model="accountForm.SysEvent.IsUserIdleTime" :true-label="1"
                :false-label="0">键鼠无操作检测</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12" v-if="accountForm.SysEvent.IsUserIdleTime === 1" style="margin-top:-15px;">
            <el-form-item label='键鼠无操作时长：' prop="SysEvent.UserIdleTime">
              <el-input v-model.number="accountForm.SysEvent.UserIdleTime" style="width:295px;"
                oninput="value=value.replace(/[^0-9]/g,'')" maxlength="3"><span slot="append">分</span></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleOther">
          <el-divider content-position="left">行为日志采集规则内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='行为日志采集：' prop="Log.Chat">
              <el-checkbox v-model="accountForm.Log.Chat" :true-label="1" :false-label="0">记录沟通回溯日志</el-checkbox>
              <el-checkbox v-model="accountForm.Log.Screen" :true-label="1" :false-label="0">记录屏幕录像日志</el-checkbox>
              <el-checkbox v-model="accountForm.Log.Trace" :true-label="1" :false-label="0">记录工作流水日志</el-checkbox>
              <el-checkbox v-model="accountForm.Log.WindowsProo" :true-label="1" :false-label="0">记录工作绩效日志</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12" v-if="accountForm.Log.Screen === 1" style="margin-top:-15px;">
            <el-form-item label='屏幕录像采集间隔：' prop="Log.ScreenInterval">
              <el-input v-model.number="accountForm.Log.ScreenInterval" style="width:295px;"
                oninput="value=value.replace(/[^0-9]/g,'')" maxlength="3"><span slot="append">秒</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="12" v-if="accountForm.Log.Screen === 1" style="margin-top:-15px;">
            <el-form-item label='屏幕录像图像质量：' prop="Log.ScreenQuality">
              <el-select v-model.number="accountForm.Log.ScreenQuality" style="width:295px;">
                <el-option label="25" :value="25"></el-option>
                <el-option label="50" :value="50"></el-option>
                <el-option label="75" :value="75"></el-option>
                <el-option label="100" :value="100"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false;">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import { getDeviceObjDisplay, DeviceObjTypeFormatter } from '@/utils/index.js';
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Sortable from "sortablejs";
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
export default {
  directives: { elDragDialog },
  components: {
    DeviceObjectSelector
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      RoleList: [],
      DepartmentList: [],
      AssetsList: [],
      DeviceObjList: [],
      Action: 0,
      dialogVisible: false,
      accountForm: {
        IsValid: 1,
        DeviceObjType: 1,
        BasicOSLog: {
          global: {
            time_window: 10,
            check_interval: 30
          },
          os_event_filter_rule: {
            id_type: 0,
            level: [1, 2, 3, 4, 5, 6, 7],
            id_list: [],
            type: [1, 2, 3, 4, 5, 6]
          }
        },
        ResPerfCheck: {
          Enabled: 0,
          CheckInterval: 30,
          MaxDiskPercent: 90,
          MaxCPUKeepTimes: 3,
          MaxCPUPercent: 90,
          MaxMEMKeepTimes: 3,
          MaxMEMPercent: 90,
        },
        SysEvent: {
          HardwareChanged: 1,
          SoftwareChanged: 1,
          USBStorage: 1,
          ExceptPowerOff: 1,
          ConnectInternet: 1,
          ConnectInternetNotLanNetcard: 1,
        },
        Log: {
          Chat: 1,
          Screen: 1,
          Trace: 1,
          WindowsProo: 1,
        }
      },
      auditAction: 1,
      auditdialog: false,
      OBJList: '',
      rules: {
        RuleName: [
          { required: true, message: "请输入策略名称" }
        ],
        'BasicOSLog.global.time_window': [
          {
            validator: (rule, value, callback) => {
              // 判断是否必填
              const isEnabled = this.accountForm.BasicOSLog.global.Enabled === 1;
              if (isEnabled && (!value && value !== 0)) {
                callback(new Error('请输入时间窗口'));
                return;
              }
              // 如果值为空且非必填，直接通过
              if (!value && value !== 0) {
                callback();
                return;
              }
              // 转换为数字并校验范围
              const num = Number(value);
              if (isNaN(num)) {
                callback(new Error('请输入数字'));
              } else if (num < 0 || num > 1440) {
                callback(new Error('请输入0-1440之间的数字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        'BasicOSLog.global.check_interval': [
          {
            validator: (rule, value, callback) => {
              // 判断是否必填
              const isEnabled = this.accountForm.BasicOSLog.global.Enabled === 1;
              if (isEnabled && (!value && value !== 0)) {
                callback(new Error('请输入检查间隔'));
                return;
              }
              // 如果值为空且非必填，直接通过
              if (!value && value !== 0) {
                callback();
                return;
              }
              // 转换为数字并校验范围
              const num = Number(value);
              if (isNaN(num)) {
                callback(new Error('请输入数字'));
              } else if (num < 3 || num > 60) {
                callback(new Error('请输入3-60之间的数字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        'ResPerfCheck.MaxCPUKeepTimes': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 1 || num > 1000) {
                  callback(new Error('请输入1-1000之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'ResPerfCheck.MaxMEMKeepTimes': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 1 || num > 1000) {
                  callback(new Error('请输入1-1000之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'BasicOSLog.os_event_filter_rule.id_list': [
          {
            validator: (rule, value, callback) => {
              // 根据 Enabled 判断是否必填
              const isEnabled = this.accountForm.BasicOSLog.global.Enabled !== 0;
              if (isEnabled && !value) {
                callback(new Error('请输入事件ID'));
                return;
              }
              // 如果值为空且非必填，直接通过
              if (!value) {
                callback();
                return;
              }
              // 分割成数组并校验
              const ids = value.split(',').map(id => id.trim()).filter(id => id !== '');
              if (ids.length === 0) {
                if (isEnabled) {
                  callback(new Error('请输入至少一个有效的事件ID'));
                } else {
                  callback();
                }
                return;
              }
              // 校验每个ID
              for (const id of ids) {
                const num = Number(id);
                if (isNaN(num)) {
                  callback(new Error('事件ID必须是数字'));
                  return;
                }
                if (num < 0 || num > 65535) {
                  callback(new Error('每个事件ID必须在0-65535之间'));
                  return;
                }
              }
              callback();
            },
            trigger: 'blur'
          }
        ],
        'ResPerfCheck.MaxDiskPercent': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 0 || num > 100) {
                  callback(new Error('请输入0-100之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'ResPerfCheck.MaxCPUPercent': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 0 || num > 100) {
                  callback(new Error('请输入0-100之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'ResPerfCheck.MaxMEMPercent': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 0 || num > 100) {
                  callback(new Error('请输入0-100之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'SysEvent.UserIdleTime': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 判断是否必填
              const isEnabled = this.accountForm.SysEvent.IsUserIdleTime === 1;
              if (isEnabled && (!value && value !== 0)) {
                callback(new Error('键鼠无操作时长'));
                return;
              }
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 10 || num > 600) {
                  callback(new Error('请输入10-600之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'Log.ScreenInterval': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 判断是否必填
              const isEnabled = this.accountForm.Log.Screen === 1;
              if (isEnabled && (!value && value !== 0)) {
                callback(new Error('请输入屏幕录像采集间隔'));
                return;
              }
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 10 || num > 600) {
                  callback(new Error('请输入10-600之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
        'Log.ScreenQuality': [
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              // 判断是否必填
              const isEnabled = this.accountForm.Log.Screen === 1;
              if (isEnabled && (!value && value !== 0)) {
                callback(new Error('请输入录像图像质量'));
                return;
              }
              // 如果值为空，直接通过（非必填）
              if (!value && value !== 0) {
                callback();
              } else {
                // 转换为数字并校验范围
                const num = Number(value);
                if (isNaN(num)) {
                  callback(new Error('请输入数字'));
                } else if (num < 25 || num > 100) {
                  callback(new Error('请选择25-100之间的数字'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur' // 失去焦点时触发校验
          }
        ],
      }
    }
  },
  watch: {
    Action() {
      this.$nextTick(() => {
        this.initSort()
      })
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetDevice()
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initSort();
  },
  methods: {
    DeviceObjTypeFormatter,
    getDeviceObjDisplay,
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    // 获取所有资产
    async GetDevice() {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
      }
      const res = await connrequest('GetDevice', data)
      this.AssetsList = res.Data
    },
    initSort() {
      document.querySelectorAll('.draggable-table').forEach(table => {
        const el = table.querySelector('.el-table__body-wrapper > table > tbody');
        const tableId = table.getAttribute('table-id');
        new Sortable(el, {
          animation: 500,
          onEnd: async (evt) => {
            if (tableId === 'table1') {
              const currRow = this.tableData.splice(evt.oldIndex, 1)[0];
              this.tableData.splice(evt.newIndex, 0, currRow);
              const newData = [];
              this.tableData.forEach((item, index) => {
                newData[index] = {
                  id: item.id,
                  rank: index + 1
                };
              });
              const data = {
                Filter: {
                  FileName: 'rule_dc_data.json'
                },
                Data: this.tableData
              };
              const res = await connrequest('SetUICommonParam', data);
              if (res.Status.StatusCode === 0) {
                this.$message.success('排序成功');
                this.getData();
              }
            }
          }
        });
      });
    },
    async getData() {
      const data = {
        Filter: {
          FileName: 'rule_dc_data.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.tableData = res.Data || []
    },
    scrollToTop() {
      this.$nextTick(() => {
        if (this.$refs.accountForm) {
          this.$refs.accountForm.scrollTop = 0;
        }
      });
    },
    addClick() {
      this.Action = 1;
      this.$nextTick(() => {
        // 等待组件挂载
        this.accountForm = {
          IsValid: 1,
          DeviceObjType: 1,
          BasicOSLog: {
            global: {
              Enabled: 0,
              time_window: 10,
              check_interval: 30
            },
            os_event_filter_rule: {
              id_type: 0,
              level: [1, 2, 3, 4, 5, 6, 7],
              id_list: [],
              type: [1, 2, 3, 4, 5, 6]
            }
          },
          ResPerfCheck: {
            Enabled: 0,
            CheckInterval: 30,
            MaxDiskPercent: 90,
            MaxCPUKeepTimes: 3,
            MaxCPUPercent: 90,
            MaxMEMKeepTimes: 3,
            MaxMEMPercent: 90,
          },
          SysEvent: {
            HardwareChanged: 1,
            SoftwareChanged: 1,
            USBStorage: 1,
            ExceptPowerOff: 1,
            ConnectInternet: 1,
            ConnectInternetNotLanNetcard: 1,
            IsUserIdleTime: 1,
            UserIdleTime: 30
          },
          Log: {
            Chat: 1,
            Screen: 1,
            Trace: 1,
            WindowsProo: 1,
            ScreenInterval: 60,
            ScreenQuality: 75,
          }
        };
        this.$refs['accountForm'].resetFields();
        // 滚动到顶部
        this.scrollToTop()
      });
      this.dialogVisible = true;
    },
    insertClick(row, index) {
      this.Action = 3
      this.tableindex = index
      this.$nextTick(() => {
        // 等待组件挂载
        this.accountForm = {
          IsValid: 1,
          DeviceObjType: 1,
          BasicOSLog: {
            global: {
              Enabled: 0,
              time_window: 10,
              check_interval: 30
            },
            os_event_filter_rule: {
              id_type: 0,
              level: [1, 2, 3, 4, 5, 6, 7],
              id_list: [],
              type: [1, 2, 3, 4, 5, 6]
            }
          },
          ResPerfCheck: {
            Enabled: 0,
            CheckInterval: 30,
            MaxDiskPercent: 90,
            MaxCPUKeepTimes: 3,
            MaxCPUPercent: 90,
            MaxMEMKeepTimes: 3,
            MaxMEMPercent: 90,
          },
          SysEvent: {
            HardwareChanged: 1,
            SoftwareChanged: 1,
            USBStorage: 1,
            ExceptPowerOff: 1,
            ConnectInternet: 1,
            ConnectInternetNotLanNetcard: 1,
            IsUserIdleTime: 1,
            UserIdleTime: 30
          },
          Log: {
            Chat: 1,
            Screen: 1,
            Trace: 1,
            WindowsProo: 1,
            ScreenInterval: 60,
            ScreenQuality: 75,
          }
        };
        this.$refs['accountForm'].resetFields();
        // 滚动到顶部
        this.scrollToTop()
      });
      this.dialogVisible = true;
    },
    changeClick(row, index) {
      this.tableindex = index;
      this.Action = 2;
      this.$nextTick(() => {
        this.accountForm = JSON.parse(JSON.stringify(row)); // 深拷贝
        // 转换 id_list
        if (this.accountForm?.BasicOSLog?.os_event_filter_rule?.id_list &&
          Array.isArray(this.accountForm.BasicOSLog.os_event_filter_rule.id_list)) {
          this.accountForm.BasicOSLog.os_event_filter_rule.id_list =
            this.accountForm.BasicOSLog.os_event_filter_rule.id_list.join(',');
        }
        // this.$refs['accountForm'].resetFields();
        // 滚动到顶部
        this.scrollToTop()
      });
      this.dialogVisible = true;
    },
    deleteClick(tableData, index) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        tableData.splice(index, 1)
        const data = {
          Filter: {
            FileName: 'rule_dc_data.json'
          },
          Data: tableData
        }
        const res = await connrequest('SetUICommonParam', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changeSysLog(val) {
      if (val) {
        this.$alert('打开后请配置好采集条件，全部采集可能会导致数据量特别大，导致系统缓慢！', '提示信息', {
          confirmButtonText: '确定',
          callback: action => {
            if (action === 'cancel') {
              this.$set(this.accountForm.BasicOSLog.global, 'Enabled', 0)
            }
          }
        });
      }
    },
    stringToNumberArray(str) {
      if (!str) return []; // 处理空输入
      return [...new Set(str.split(',').filter(Boolean).map(Number).filter(num => !isNaN(num)))];
    },
    submit() {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if (this.Action !== 2 && this.tableData.findIndex(item => item.RuleName === this.accountForm.RuleName) !== -1) {
            this.$message.error('该规则已经存在')
            return false
          }
          if (this.accountForm.DeviceObjType === 2) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择部门')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 8) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择角色')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 6) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择资产')
              return false
            }
          }
          if (this.accountForm.BasicOSLog.os_event_filter_rule.id_type !== 0) {
            if (!this.accountForm.BasicOSLog.os_event_filter_rule.id_list) {
              this.$message.error('事件ID不能为空')
              return false
            }
          }
          let data = {}
          const idList = this.accountForm?.BasicOSLog?.os_event_filter_rule?.id_list;
          if (idList && idList.length > 0) {
            this.accountForm.BasicOSLog.os_event_filter_rule.id_list = this.stringToNumberArray(idList);
          }
          if (this.Action === 1) {
            data = {
              Filter: {
                FileName: 'rule_dc_data.json'
              },
              Data: [
                ...this.tableData,
                {
                  ...this.accountForm,
                  RuleID: Math.floor(Date.now() / 1000)
                }
              ]
            }
          }
          if (this.Action === 2) {
            this.tableData[this.tableindex] = this.accountForm
            data = {
              Filter: {
                FileName: 'rule_dc_data.json'
              },
              Data: this.tableData
            }
          }
          if (this.Action === 3) {
            this.tableData.splice(this.tableindex + 1, 0, { ...this.accountForm, RuleID: Math.floor(Date.now() / 1000) })
            data = {
              Filter: {
                FileName: 'rule_dc_data.json'
              },
              Data: this.tableData
            }
          }
          const res = await connrequest('SetUICommonParam', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success(this.Action == 1 ? '添加成功' : '修改成功')
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    }
  }
}
</script>